package com.cyw.common.config.mybatis.handler.base;

import com.cyw.common.exceptions.BaseException;
import com.cyw.common.utils.JsonUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/**
 * @Author:cyw
 * @CreateTime: 2021/3/3 17:18
 **/
@MappedTypes(List.class)
@MappedJdbcTypes(value = {JdbcType.BLOB, JdbcType.VARCHAR, JdbcType.CHAR})
public abstract class ListJsonTypeHandler<T> extends BaseTypeHandler<List<T>> {


    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, List<T> parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, serializer(parameter));
    }

    @Override
    public List<T> getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String info = rs.getString(columnName);
        return deserializer(info);
    }

    @Override
    public List<T> getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return deserializer(rs.getString(columnIndex));
    }

    @Override
    public List<T> getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return deserializer(cs.getString(columnIndex));
    }

    private String serializer(List<T> parameter) {
        return JsonUtils.toJsonIfPresent(parameter);
    }

    protected List<T> deserializer(String info) {
        throw new BaseException("根据泛型类型 重写反序列化方法");
    }

}

    
    
    
    
    
    
    
    
    

    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    